package cn.myframe.log.aspect;


import cn.myframe.log.LogPojo;
import cn.myframe.log.event.LogSaveEvent;
import cn.myframe.utils.HttpContextUtils;
import cn.myframe.utils.IPUtils;
import cn.myframe.utils.SpringContextUtils;
import cn.myframe.utils.core.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 删除数据时,保存修改记录
 * 
 * @author ynz
 * @email ynz@myframe.cn
 * @date 2018年7月31日 下午11:19:38
 */
@Aspect
@Component
@Slf4j
public class DeleteLogAspect {
	
	@Autowired
    ApplicationContext applicationContext;
	
	@Around("@annotation(cn.myframe.log.annotation.LogDelete) || execution(* cn.myframe.controller..*.delete(..))")
	public Object deal(ProceedingJoinPoint  joinPoint) throws Throwable{
		log.debug("operator [delete] method!");
		Object o = null;
		boolean flag = true;
		LogPojo logPojo = new LogPojo();
		try {
			MethodSignature signature = (MethodSignature) joinPoint.getSignature();
			Method method = signature.getMethod();
			//请求的参数
			Object[] args = joinPoint.getArgs();
			//请求的方法名
			String className = joinPoint.getTarget().getClass().getName();
			String methodName = signature.getName();
		
			//执行controller类的INFO方法
			Object bean = SpringContextUtils.getBean(method.getDeclaringClass());
			Method controllerMethod = method.getDeclaringClass().getDeclaredMethod("info", Long.class);
			
			List<Object> ids = JSON.parseArray(JSON.toJSONString(args[0]), Object.class);
			for(Object objectId : ids){
				R result = (R)controllerMethod.invoke(bean, Long.valueOf(objectId.toString()));
				String returnReslut = JSON.toJSONStringWithDateFormat(result, JSON.DEFFAULT_DATE_FORMAT);
				
				//获取request
				HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
				//设置IP地址
				logPojo.setIp(IPUtils.getIpAddr(request));
				logPojo.setType(2);
				logPojo.setOperation("logDelData");
				logPojo.setMethod(className+"."+methodName+"()");
				logPojo.setParams(JSON.toJSONStringWithDateFormat(args[0], JSON.DEFFAULT_DATE_FORMAT));
				logPojo.setClassName(className.substring(className.lastIndexOf(".")+1));
				logPojo.setOperateValue(returnReslut);
				applicationContext.publishEvent(new LogSaveEvent(this,logPojo));
			}
			//执行具体的方法
			o = joinPoint.proceed();
			flag = false;
		} catch (Exception e) {
			log.error("[delete] method,write log fail!");
			if(flag){
				o = joinPoint.proceed();
			}
		}
		return o;
	}
	
	
	
}
